package com.repair.controller;

import com.repair.entity.Announcement;
import com.repair.entity.User;
import com.repair.service.AnnouncementService;
import com.repair.service.UserService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/admin/announcements")
@PreAuthorize("hasRole('ADMIN')")
public class AdminAnnouncementController {
    
    @Autowired
    private AnnouncementService announcementService;

    @Autowired
    private UserService userService;
    
    @PostMapping
    public ResponseEntity<Announcement> create(@RequestBody Announcement announcement,
                                            @AuthenticationPrincipal UserDetails userDetails) {
        User admin = userService.getByUsername(userDetails.getUsername());
        announcement.setCreatedBy(admin.getId());
        return ResponseEntity.ok(announcementService.create(announcement));
    }
    
    @PutMapping("")
    public ResponseEntity<Void> update(@RequestBody Announcement announcement) {
        announcement.setId(announcement.getId());
        announcementService.update(announcement);
        return ResponseEntity.ok().build();
    }
    
    @PutMapping("/{id}/publish")
    public ResponseEntity<Void> publish(@PathVariable Long id) {
        announcementService.publish(id);
        return ResponseEntity.ok().build();
    }
    
    @PutMapping("/{id}/offline")
    public ResponseEntity<Void> offline(@PathVariable Long id) {
        announcementService.offline(id);
        return ResponseEntity.ok().build();
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<Announcement> getById(@PathVariable Long id) {
        return ResponseEntity.ok(announcementService.getById(id));
    }
    
    @GetMapping
    public ResponseEntity<List<Announcement>> getAll() {
        return ResponseEntity.ok(announcementService.getAll());
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        announcementService.deleteAnnouncement(id);
        return ResponseEntity.ok().build();
    }
} 